//
//  WYMainViewController.m
//  WYLocalCode
//
//  Created by longtu on 15/5/14.
//  Copyright (c) 2015年 longtu. All rights reserved.
//

#import "WYMainViewController.h"

#import "WYLocalCodeView.h"

@interface WYMainViewController () <UITextFieldDelegate>

@property (nonatomic, retain) UITextField *input;
@property (nonatomic, retain) WYLocalCodeView *localCodeView;

@end

@implementation WYMainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.localCodeView = [[WYLocalCodeView alloc] initWithFrame:CGRectMake(60, 20, self.view.frame.size.width-120, 40)];
    [self.view addSubview:self.localCodeView];
    
    self.input = [[UITextField alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 40)];
    self.input.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.input.layer.borderWidth = 2.0;
    self.input.layer.cornerRadius = 5.0;
    self.input.font            = [UIFont systemFontOfSize:21];
    self.input.placeholder     = @"请输入验证码!";
    self.input.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.input.backgroundColor = [UIColor clearColor];
    self.input.textAlignment   = NSTextAlignmentCenter;
    self.input.returnKeyType   = UIReturnKeyDone;
    self.input.delegate        = self;
    [self.view addSubview:self.input];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if ([self.input.text isEqualToString:self.localCodeView.changeString]) {
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"ROFLOL" message:@"LOL" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alview show];
    }else{
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
        anim.repeatCount = 1;
        anim.values = @[@-20, @20, @-20];
        [self.localCodeView.layer addAnimation:anim forKey:nil];
        [self.input.layer addAnimation:anim forKey:nil];
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (self.input){
        if ([toBeString length] > 4) {
            self.input.text = [toBeString substringToIndex:4];
            return NO;
        }
    }
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
